<template>
  <div>
    <el-input placeholder="文件路径" readonly v-model="fileString" class="input-with-select">
      <div slot="append">
        <el-upload
          :auto-upload="false"
          :action="docLoadPath"
          :show-file-list="false"
          :on-change="handlePreview"
        >
          <el-button type="primary" :loading="loading">点击上传</el-button>
        </el-upload>
      </div>
    </el-input>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: 'fileUpLoad',
  props: {
    fileUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      docLoadPath: this.$API.HOST_SERVER_URL + this.$API.HOST_FILE_UPLOAD,
      token: '123',
      fileString: ''
    };
  },
  watch: {
    fileUrl(val) {
      console.log('val',val);
      this.fileString = val;
    }
  },
  created() {
    if (this.fileUrl) {
      this.fileString = this.fileUrl;
    }
  },
  methods: {
    //身份证正面上传成功
    handlePreview(file) {
      var FileExt = file.name.replace(/.+\./, '');
      if (
        ['docx', 'doc', 'pdf', 'xlsx', 'xls'].indexOf(FileExt.toLowerCase()) ===
        -1
      ) {
        this.$message({
          type: 'warning',
          message: '请上传docx,doc,pdf,xlsx,xls格式文件！'
        });
        return false;
      }
      let formData=new FormData();
      formData.append('files',file.raw)
      this.uploadAjaxMethod(formData)
    },
    uploadAjaxMethod(formData) {
      this.loading = true;
      axios.post(this.docLoadPath,formData)
        .then(res => {
          this.loading = false;
          if(res.data.code === 1 && Array.isArray(res.data.data.fileNames) && res.data.data.fileNames.length>0){
            const fileName=res.data.data.fileNames[0];
            console.log('fileName',fileName)
            this.$emit('update:fileUrl', fileName);
            this.$message.success('上传成功');
          }else{
            this.$message.fail('上传失败');
          }
        })
        .catch(err => {
          this.loading = false;
        });
    }
  }
};
</script>

<style scoped>
.input-with-select {
}
</style>
